package com.rchat.pocmini.activity;

import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;

import com.itsdf07.alog.ALog;
import com.rchat.pocmini.R;
import com.rchat.pocmini.account.PocAccount;
import com.rchat.pocmini.activity.adapter.PushMessageOnLineAdapter;
import com.rchat.pocmini.activity.bean.PushMessageOnLineBean;
import com.rchat.pocmini.activity.fragment.FriendFragment;
import com.rchat.pocmini.activity.fragment.groups.GroupsPresenterImpl;
import com.rchat.pocmini.bean2eventbus.UpdateGroupBean;
import com.rchat.pocmini.common.BaseActivity;
import com.rchat.pocmini.global.BundleKeyGlobal;
import com.rchat.pocmini.global.HttpCodeGlobal;
import com.rchat.pocmini.global.RequestParam;
import com.rchat.pocmini.global.UrlsGlobal;
import com.rchat.pocmini.util.HttpUtil;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by ljd on 2017/3/13.
 */

public class PushMessageReceiveActivity extends BaseActivity implements View.OnClickListener {

    private ImageView ivBack;
    private ListView lvPushMessage;
    private List<PushMessageOnLineBean> dataList;
    private PushMessageOnLineAdapter adapter;
    private int typeCode;
    private String groupId;

    private static final int QUERY_ADD_FRIEND_PUSH = 1;
    private static final int QUERY_APPLY_GROUP_PUSH = 2;
    private static final int QUERY_REPLY_PUSH = 3;


    private void initData() {
        String jsonContent = getIntent().getStringExtra(BundleKeyGlobal.BUNDLE_JPUSH_EXTRA_MESSAGE);
        typeCode = getIntent().getIntExtra(BundleKeyGlobal.BUNDLE_JPUSH_TYPECODE, 0);
        if (typeCode == 0) {
            return;
        }
        dataList = new ArrayList<>();
        adapter = new PushMessageOnLineAdapter(this, dataList);
        lvPushMessage.setAdapter(adapter);
        dealPushTypeCode(jsonContent, typeCode);
    }

    private void dealPushTypeCode(String jsonContent, int typeCode) {
        ALog.d("typeCode = %s", typeCode);
        switch (typeCode) {
            case 1130:
                //加好友
                try {
                    String requestJson = createQueryAddFriendPushMessageJson(PocAccount.getUserId());
                    startThread(requestJson, UrlsGlobal.getUrl(UrlsGlobal.QUERY_ADD_FRIEND_PUSH), QUERY_ADD_FRIEND_PUSH);

                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case 1121:
                //请求加入群组
                try {
                    JSONObject obj = new JSONObject(jsonContent);
                    JSONObject data = obj.getJSONObject("data");
                    String userName = data.getString("userName");
                    groupId = data.getString("groupId");
                    String requestJson = createQueryAgreeJoinGroupPushJson(groupId);
                    startThread(requestJson, UrlsGlobal.getUrl(UrlsGlobal.QUERY_APPLY_GROUP_PUSH), QUERY_APPLY_GROUP_PUSH);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case 1120:
                //邀请进群组推送
                String requestJson = createQueryReplyPushJson(PocAccount.getUserId(), typeCode);
                startQueryReplyPushThread(requestJson);
                break;
            case 1131:
                //答复加好友推送
                String requestJson1 = createQueryReplyPushJson(PocAccount.getUserId(), typeCode);
                startQueryReplyPushThread(requestJson1);
                break;
            case 1122:
                //答复申请群组
            case 1123:
                //查看成员退群、解散群组通知
                String requestJson2 = createQueryReplyPushJson(PocAccount.getUserId(), typeCode);
                startQueryReplyPushThread(requestJson2);
                break;
        }

    }

    private void startQueryReplyPushThread(final String requestJson) {
        Thread thread = new Thread() {
            @Override
            public void run() {
                String backJson = HttpUtil.httpConnect(UrlsGlobal.getUrl(UrlsGlobal.QUERY_REPLY_PUSH), requestJson, HttpUtil.HTTP_POST);
                Message m = new Message();
                m.what = QUERY_REPLY_PUSH;
                m.obj = backJson;
                handler.sendMessage(m);
            }
        };
        thread.start();
    }


    @Override
    public void initView() {
        ivBack = (ImageView) findViewById(R.id.iv_back);
        ivBack.setOnClickListener(this);
        lvPushMessage = (ListView) findViewById(R.id.list_view_push_message_on_line);

        initData();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                this.finish();
                break;
        }
    }

    /**
     * 生成查询加好友推送消息json
     *
     * @return 请求json
     */
    private String createQueryAddFriendPushMessageJson(String userName) {
        Map<String, String> param = new HashMap<>();
        param.put("userName", userName);
        //body = {"code":1038,"data":{"platform":1,"version":"1.0","enterprise":1,"userName":"111110000118"}}
        String body = RequestParam.requestRootParam(HttpCodeGlobal.REQ_CODE_1038, param);
        return body;
    }

    /**
     * 生成查询邀请群组、答复邀请群组、答复加好友推送、查看成员退群、解散群组通知json
     *
     * @param userName 用户PocId
     * @param typeCode 如 1120
     * @return
     */
    private String createQueryReplyPushJson(String userName, int typeCode) {
        Map<String, String> param = new HashMap<>();
        param.put("userName", userName);
        param.put("pushCode", typeCode + "");

        //body = {"code":1017,"data":{"platform":1,"version":"1.0","enterprise":1,"pushCode":"1123","userName":"111110000118"}}
        String body = RequestParam.requestRootParam(HttpCodeGlobal.REQ_CODE_1017, param);
        return body;
    }


    /**
     * 生成查询加入群组推送json
     *
     * @return 请求json
     */
    private String createQueryAgreeJoinGroupPushJson(String groupId) {
        Map<String, String> param = new HashMap<>();
        param.put("groupId", groupId);
        //body = {"code":1034,"data":{"platform":1,"version":"1.0","enterprise":1,"userName":"111110000118"}}
        String body = RequestParam.requestRootParam(HttpCodeGlobal.REQ_CODE_1029, param);
        return body;
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {
                case QUERY_ADD_FRIEND_PUSH:
                    String json = (String) msg.obj;
                    if (json == null || json.equals("")) {
                        break;
                    }
                    try {
                        JSONObject obj = new JSONObject(json);
                        if (obj.getString("code").equals("200")) {
                            dataList.clear();
                            JSONObject data = obj.getJSONObject("data");
                            JSONObject users = data.getJSONObject("users");
                            JSONArray user = users.getJSONArray("user");

                            for (int i = 0; i < user.length(); i++) {
                                PushMessageOnLineBean bean = new PushMessageOnLineBean();
                                bean.setUserName(user.getJSONObject(i).getString("userName"));
                                bean.setDisplayName(user.getJSONObject(i).getString("display"));
                                bean.setCreateTime(user.getJSONObject(i).getString("createTime"));
                                bean.setType(PushMessageOnLineBean.APPLY_FRIEND);
                                dataList.add(bean);
                            }


                            adapter.notifyDataSetChanged();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                case QUERY_APPLY_GROUP_PUSH:
                    String s = (String) msg.obj;
                    if (s == null || s.equals("")) {
                        break;
                    }
                    try {
                        JSONObject obj = new JSONObject(s);
                        if (obj.getString("code").equals("200")) {
                            dataList.clear();
                            JSONObject data = obj.getJSONObject("data");
                            JSONArray applyGroups = data.getJSONArray("applyGroups");

                            for (int i = 0; i < applyGroups.length(); i++) {
                                PushMessageOnLineBean bean = new PushMessageOnLineBean();
                                bean.setDisplayName(applyGroups.getJSONObject(i).getString("displayName"));
                                bean.setGroupName(applyGroups.getJSONObject(i).getString("groupName"));
                                bean.setUserName(applyGroups.getJSONObject(i).getString("userName"));
                                bean.setGroupId(applyGroups.getJSONObject(i).getString("groupId"));
                                bean.setCreateTime(applyGroups.getJSONObject(i).getString("createTime"));
                                bean.setType(PushMessageOnLineBean.APPLY_GROUP);
                                dataList.add(bean);
                            }
                            adapter.notifyDataSetChanged();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                case QUERY_REPLY_PUSH:
                    String ss = (String) msg.obj;
                    if (ss == null || ss.equals("")) {
                        break;
                    }
                    try {
                        JSONObject o = new JSONObject(ss);
                        if (o.getString("code").equals("200")) {
                            dataList.clear();
                            JSONObject data = o.getJSONObject("data");
                            JSONArray replyPushes = data.getJSONArray("replyPushs");
                            for (int i = 0; i < replyPushes.length(); i++) {
                                PushMessageOnLineBean bean = new PushMessageOnLineBean();
                                bean.setCreateTime(replyPushes.getJSONObject(i).getString("createTime"));
                                bean.setMessage(replyPushes.getJSONObject(i).getString("message"));
                                //类型可以都使用REPLY_FRIEND，因为后台接口一样
                                bean.setType(PushMessageOnLineBean.REPLY_FRIEND);
                                dataList.add(bean);
                            }
                            adapter.notifyDataSetChanged();
                            FriendFragment.instance.queryFriend();
                            UpdateGroupBean bean = new UpdateGroupBean();
                            bean.setTarget(this.getClass(), GroupsPresenterImpl.class, "onEventBusUpdateGroups");
                            bean.setCurrentEvent(UpdateGroupBean.EVENT_GROPULIST_UPDATE);
                            EventBus.getDefault().post(bean);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
            }
        }
    };

    /**
     * @param requestJson 请求json
     */
    private void startThread(final String requestJson, final String url, final int type) {
        Thread thread = new Thread() {
            @Override
            public void run() {
                String backJson = HttpUtil.httpConnect(url, requestJson, HttpUtil.HTTP_POST);
                Message m = new Message();
                if (type == QUERY_ADD_FRIEND_PUSH) {
                    m.what = QUERY_ADD_FRIEND_PUSH;
                    m.obj = backJson;
                    handler.sendMessage(m);
                } else if (type == QUERY_APPLY_GROUP_PUSH) {
                    m.what = QUERY_APPLY_GROUP_PUSH;
                    m.obj = backJson;
                    handler.sendMessage(m);
                }
            }
        };
        thread.start();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        this.finish();
    }

    @Override
    public void onResume() {
        super.onResume();
        //友盟自定义统计开始
        MobclickAgent.onPageStart("PushMessageReceiverActivity");
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    public int getLayoutId() {
        return R.layout.push_message_receive_activity_layout;
    }
}
